package com.delaphone.flocash.web.action;

import com.delaphone.flocash.service.AccountService;
import com.delaphone.flocash.web.service.MailService;
import com.delaphone.flocash.service.SystemService;
import com.delaphone.flocash.service.UserService;
import com.delaphone.flocash.util.StringUtil;
import com.delaphone.flocash.web.util.Validate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.jpos.gl.Currency;
import org.jpos.gl.GLEntry;

/**
 *
 * @author dongtv
 */
public class SendCashAction extends BaseAction {

    private String sendTo;
    private String amount;
    private String currency;
    private String currCode;
    private String email_subject;
    private String note;
    private UserService userService;
    private AccountService accountService;
    private MailService mailService;
    private SystemService sysService;
    private BigDecimal balance;
    private BigDecimal newBalance;
    private ArrayList<Currency> currencies;

    public String step1() {
        if (user == null) {
            return LOGIN;
        }
        sendTo = "";
        amount = "";
        email_subject = "Payment from " + user.getEmail();
        note = "";
        return SUCCESS;
    }

    public String step2() {
        if (user == null) {
            return LOGIN;
        }
        validateFields();
        if (getFieldErrors().size() > 0 || getActionErrors().size() > 0) {
            return INPUT;
        } else {
            balance = user.getBalance();
            newBalance = balance.subtract(new BigDecimal(amount));
            return SUCCESS;
        }
    }

    public String step3() {
         if (user == null) {
            return LOGIN;
        }
        validateFields();
        if (getFieldErrors().size() > 0 || getActionErrors().size() > 0) {
            return INPUT;
        } else {
            String dest = userService.getAccountByEmail(sendTo, currency);
            if (accountService.sendCash(user.getAccount(), dest, new BigDecimal(amount), sendTo, note)) {
                //send mail notic
                String mail = getText("user.send.mailContent", new String[]{user.getEmail(), (amount + " " + getText("currency." + user.getCurrency())), note});
                mailService.sendMail(sendTo, getText("user.send.mailTitle"), mail);
                return SUCCESS;
            } else {
                return ERROR;
            }
        }
    }

    public void validateFields() {
        //check empty
        if (Validate.isEmptyString(sendTo) || !Validate.isEmail(sendTo)) {
            addFieldError(sendTo, "Invalid destination account");
        }
        if (Validate.isEmptyString(amount) || !Validate.isNumber(amount)) {
            addFieldError(amount, "Invalid Amount");
        }
        //check valid
        if (!userService.checkUserExist(sendTo)) {
            addActionError("Account " + sendTo + " is not exist!");
        }
        BigDecimal amt = new BigDecimal(amount);
        BigDecimal currBalance = accountService.getAccountBalance(user.getAccount());
        if (currBalance.compareTo(amt) < 0) {
            addActionError("Not enough balance to make the transaction!");
            return;
        }
        //check transaction limit
        if (user.getTxLimit().compareTo(amt) < 0) {
            addActionError("Exceed transaction limit!");
            return;
        }
        //check daily limit
        Iterator<GLEntry> todayTx = userService.getTransHistory(user.getEmail(), user.getCurrency(), StringUtil.getDateForSQL(new Date()), StringUtil.getDateForSQL(new Date()), "-").iterator();
        BigDecimal sum = BigDecimal.ZERO;
        while (todayTx.hasNext()) {
            BigDecimal c = todayTx.next().getAmount();
            logger.info("Checkpoint1: " + c);
            sum = sum.add(c);
        }
        sum = sum.add(new BigDecimal(amount));
        logger.info("Sum = " + sum.toString());
        logger.info("Daily Limit = " + user.getDailyLimit().toString());
        if (sum.compareTo(user.getDailyLimit()) > 0) {
            addActionError("Exceed daily limit!");
            return;
        }
    }

// <editor-fold defaultstate="collapsed" desc="set and get method">
    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        this.amount = amount;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public String getEmail_subject() {
        return email_subject;
    }

    public void setEmail_subject(String email_subject) {
        this.email_subject = email_subject;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getSendTo() {
        return sendTo;
    }

    public void setSendTo(String sendTo) {
        this.sendTo = sendTo;
    }

    public AccountService getAccountService() {
        return accountService;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public BigDecimal getNewBalance() {
        return newBalance;
    }

    public ArrayList<Currency> getCurrencies() {
        currencies = (ArrayList<Currency>) sysService.getAllCurrencies();
        return currencies;
    }

    public void setCurrencies(ArrayList<Currency> currencies) {
        this.currencies = currencies;
    }

    public SystemService getSysService() {
        return sysService;
    }

    public void setSysService(SystemService sysService) {
        this.sysService = sysService;
    }

    public String getCurrCode() {
        return getText("currency." + currency);
    }

    public MailService getMailService() {
        return mailService;
    }

    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }
    // </editor-fold>
}
